<template>
  <view class="page-container">
    <uni-nav-bar
      :title="isViewMode ? '证照信息' : '信息更新'"
      left-icon="back"
      @click-left="goBack"
      fixed
    />

    <view class="content">
      <!-- 审核状态（查看模式显示） -->
      <view v-if="isViewMode && merchantData?.data" class="audit-status-card">
        <view class="status-row">
          <text class="status-label">审核状态：</text>
          <text
            class="status-value"
            :class="getAuditStatusClass(merchantData.data.isAudit)"
          >
            {{ getAuditStatusText(merchantData.data.isAudit) }}
          </text>
        </view>
        <view v-if="merchantData.data.merchantName" class="info-row">
          <text class="info-label">门店名称：</text>
          <text class="info-value">{{ merchantData.data.merchantName }}</text>
        </view>
        <view
          v-if="merchantData.data.branchName && merchantData.data.branchName.trim()"
          class="info-row"
        >
          <text class="info-label">分店名称：</text>
          <text class="info-value">{{ merchantData.data.branchName }}</text>
        </view>
        <view v-if="merchantData.data.classifyName" class="info-row">
          <text class="info-label">类目：</text>
          <text class="info-value">{{ merchantData.data.classifyName }}</text>
        </view>
        <view v-if="getFullAddress(merchantData.data)" class="info-row">
          <text class="info-label">地址：</text>
          <text class="info-value">{{ getFullAddress(merchantData.data) }}</text>
        </view>
        <view
          v-if="merchantData.data.storeBusinessHours && merchantData.data.storeBusinessHours.trim()"
          class="info-row"
        >
          <text class="info-label">营业时间：</text>
          <text class="info-value">{{
            merchantData.data.storeBusinessHours
          }}</text>
        </view>
        <view
          v-if="merchantData.data.offerDiscountsRatio !== undefined && merchantData.data.offerDiscountsRatio !== null"
          class="info-row"
        >
          <text class="info-label">让利比率：</text>
          <text class="info-value"
            >{{ (merchantData.data.offerDiscountsRatio * 100).toFixed(2) }}%</text
          >
        </view>
        <view v-if="merchantData.data.userName" class="info-row">
          <text class="info-label">法人姓名：</text>
          <text class="info-value">{{ merchantData.data.userName }}</text>
        </view>
        <view v-if="merchantData.data.userMobile" class="info-row">
          <text class="info-label">法人手机号：</text>
          <text class="info-value">{{ merchantData.data.userMobile }}</text>
        </view>
        <view
          v-if="merchantData.data.qrcodeLink && merchantData.data.qrcodeLink.trim()"
          class="info-row qrcode-row"
        >
          <text class="info-label">二维码：</text>
          <image
            :src="merchantData.data.qrcodeLink"
            class="qrcode-image"
            mode="aspectFit"
          />
        </view>
      </view>

      <!-- 变更内容（仅编辑模式显示） -->
      <view v-if="!isViewMode">
        <view class="section-title">变更内容</view>
        <view class="checkbox-group">
          <label class="checkbox-item" @click="toggleCheckbox('license')">
            <view
              class="checkbox-box"
              :class="{ checked: selectedItems.license }"
            >
              <uni-icons
                v-if="selectedItems.license"
                type="checkmarkempty"
                color="#fff"
                size="16"
              ></uni-icons>
            </view>
            <text class="checkbox-label">营业执照</text>
          </label>
          <label class="checkbox-item" @click="toggleCheckbox('legalIdCard')">
            <view
              class="checkbox-box"
              :class="{ checked: selectedItems.legalIdCard }"
            >
              <uni-icons
                v-if="selectedItems.legalIdCard"
                type="checkmarkempty"
                color="#fff"
                size="16"
              ></uni-icons>
            </view>
            <text class="checkbox-label">法人身份证</text>
          </label>
          <label class="checkbox-item" @click="toggleCheckbox('settlement')">
            <view
              class="checkbox-box"
              :class="{ checked: selectedItems.settlement }"
            >
              <uni-icons
                v-if="selectedItems.settlement"
                type="checkmarkempty"
                color="#fff"
                size="16"
              ></uni-icons>
            </view>
            <text class="checkbox-label">结算信息</text>
          </label>
          <label class="checkbox-item" @click="toggleCheckbox('controller')">
            <view
              class="checkbox-box"
              :class="{ checked: selectedItems.controller }"
            >
              <uni-icons
                v-if="selectedItems.controller"
                type="checkmarkempty"
                color="#fff"
                size="16"
              ></uni-icons>
            </view>
            <text class="checkbox-label">店铺实控人</text>
          </label>
        </view>
      </view>

      <!-- 营业执照 -->
      <view v-if="shouldShowLicense" class="form-section">
        <view class="section-subtitle">三合一证件照/营业许可证</view>

        <view class="upload-area" @click="uploadLicense">
          <image
            v-if="licenseImage"
            :src="licenseImage"
            class="upload-image"
            mode="aspectFit"
          ></image>
          <image
            v-else
            src="/static/mine/yyzz.png"
            class="upload-placeholder"
            mode="aspectFit"
          ></image>
          <view class="upload-tip">点击上传营业执照原件</view>
        </view>

        <view class="form-item">
          <view class="form-label">注册地区</view>
          <view class="form-value" @click="selectRegion">
            <text :class="regionText ? 'value-text' : 'placeholder'">{{
              regionText || "请选择注册地区"
            }}</text>
            <uni-icons type="right" color="#999" size="16"></uni-icons>
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">营业执照名称</view>
          <view class="form-value">
            <input
              type="text"
              class="form-input"
              placeholder="请输入营业执照名称"
              v-model="licenseForm.name"
            />
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">企业地址</view>
          <view class="form-value">
            <input
              type="text"
              class="form-input"
              placeholder="请输入企业地址"
              v-model="licenseForm.address"
            />
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">社会统一信用代码</view>
          <view class="form-value">
            <input
              type="text"
              class="form-input"
              placeholder="请输入社会统一信用代码"
              v-model="licenseForm.creditCode"
            />
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">有效期开始</view>
          <view class="form-value" @click="selectStartDate">
            <text :class="licenseForm.startDate ? 'value-text' : 'placeholder'">
              {{ licenseForm.startDate || "请选择开始日期" }}
            </text>
            <uni-icons type="right" color="#999" size="16"></uni-icons>
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">有效期结束</view>
          <view class="form-value" @click="selectEndDate">
            <text :class="licenseForm.endDate ? 'value-text' : 'placeholder'">
              {{ licenseForm.endDate || "请选择结束日期" }}
            </text>
            <uni-icons type="right" color="#999" size="16"></uni-icons>
          </view>
        </view>

        <view class="form-item column">
          <view class="form-label">经营范围</view>
          <view class="form-value-full">
            <text class="value-text">{{
              licenseForm.scope ||
              "一般项目：信息咨询服务（不含许可类信息咨询服务）；技术服务、技术开发、技术咨询、技术交流、技术转让、技术推广；市场营销策划；社会经济咨询服务；企业管理；企业管理咨询（除依法须经批准的项目外，凭营业执照依法自主开展经营活动）。"
            }}</text>
          </view>
        </view>
      </view>

      <!-- 法人身份证 -->
      <view v-if="shouldShowLegalIdCard" class="form-section">
        <view class="section-subtitle">法人身份证</view>

        <view class="upload-section">
          <view class="upload-item">
            <view class="upload-label">人像面</view>
            <view class="upload-desc">上传您的身份证人像面</view>
            <view class="upload-area small" @click="uploadIdCardFront">
              <image
                v-if="idCardFrontImage"
                :src="idCardFrontImage"
                class="upload-image"
                mode="aspectFit"
              ></image>
              <image
                v-else
                src="/static/mine/rxm.png"
                class="upload-placeholder"
                mode="aspectFit"
              ></image>
            </view>
          </view>

          <view class="upload-item">
            <view class="upload-label">国徽面</view>
            <view class="upload-desc">上传您的身份证国徽面</view>
            <view class="upload-area small" @click="uploadIdCardBack">
              <image
                v-if="idCardBackImage"
                :src="idCardBackImage"
                class="upload-image"
                mode="aspectFit"
              ></image>
              <image
                v-else
                src="/static/mine/ghm.png"
                class="upload-placeholder"
                mode="aspectFit"
              ></image>
            </view>
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">法人姓名</view>
          <view class="form-value">
            <input
              type="text"
              class="form-input"
              placeholder="请输入法人姓名"
              v-model="idCardForm.name"
            />
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">身份证号</view>
          <view class="form-value">
            <input
              type="text"
              class="form-input"
              placeholder="请输入身份证号"
              v-model="idCardForm.idNumber"
            />
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">身份证起效期</view>
          <view class="form-value" @click="selectIdCardStartDate">
            <text :class="idCardForm.startDate ? 'value-text' : 'placeholder'">
              {{ idCardForm.startDate || "请选择起效期" }}
            </text>
            <uni-icons type="right" color="#999" size="16"></uni-icons>
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">身份证到期日</view>
          <view class="form-value" @click="selectIdCardEndDate">
            <text :class="idCardForm.endDate ? 'value-text' : 'placeholder'">
              {{ idCardForm.endDate || "请选择到期日" }}
            </text>
            <uni-icons type="right" color="#999" size="16"></uni-icons>
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">手机号</view>
          <view class="form-value">
            <input
              type="text"
              class="form-input"
              placeholder="请输入手机号"
              v-model="idCardForm.phone"
            />
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">身份证住址</view>
          <view class="form-value">
            <input
              type="text"
              class="form-input"
              placeholder="请输入身份证住址"
              v-model="idCardForm.address"
            />
          </view>
        </view>
      </view>

      <!-- 结算信息 -->
      <view v-if="shouldShowSettlement" class="form-section">
        <view class="section-subtitle">结算信息</view>

        <view class="tab-group">
          <view
            class="tab-item"
            :class="{ active: settlementTab === 'personal' }"
            @click="settlementTab = 'personal'"
          >
            法人银行卡
          </view>
          <view
            class="tab-item"
            :class="{ active: settlementTab === 'company' }"
            @click="settlementTab = 'company'"
          >
            企业对公账号
          </view>
        </view>

        <!-- 法人银行卡 -->
        <template v-if="settlementTab === 'personal'">
          <view class="upload-section">
            <view class="upload-item">
              <view class="upload-label">银行卡正面</view>
              <view class="upload-desc">上传银行卡正面</view>
              <view class="upload-area small" @click="uploadBankCardFront">
                <image
                  v-if="bankCardFrontImage"
                  :src="bankCardFrontImage"
                  class="upload-image"
                  mode="aspectFit"
                ></image>
                <image
                  v-else
                  src="/static/mine/yhkzm.png"
                  class="upload-placeholder"
                  mode="aspectFit"
                ></image>
              </view>
            </view>

            <view class="upload-item">
              <view class="upload-label">银行卡反面</view>
              <view class="upload-desc">上传银行卡反面</view>
              <view class="upload-area small" @click="uploadBankCardBack">
                <image
                  v-if="bankCardBackImage"
                  :src="bankCardBackImage"
                  class="upload-image"
                  mode="aspectFit"
                ></image>
                <image
                  v-else
                  src="/static/mine/yhkfm.png"
                  class="upload-placeholder"
                  mode="aspectFit"
                ></image>
              </view>
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">持卡人姓名</view>
            <view class="form-value">
              <input
                type="text"
                class="form-input"
                placeholder="请输入持卡人姓名"
                v-model="settlementForm.cardHolder"
              />
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">卡号</view>
            <view class="form-value">
              <input
                type="text"
                class="form-input"
                placeholder="请输入卡号"
                v-model="settlementForm.cardNumber"
              />
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">所属银行</view>
            <view class="form-value" @click="selectPersonalBank">
              <text :class="settlementForm.bank ? 'value-text' : 'placeholder'">
                {{ settlementForm.bank || "请选择所属银行" }}
              </text>
              <uni-icons type="right" color="#999" size="16"></uni-icons>
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">银行所在地</view>
            <view class="form-value" @click="selectPersonalBankLocation">
              <text
                :class="
                  settlementForm.bankLocation ? 'value-text' : 'placeholder'
                "
              >
                {{ settlementForm.bankLocation || "请选择银行所在地" }}
              </text>
              <uni-icons type="right" color="#999" size="16"></uni-icons>
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">开户行</view>
            <view class="form-value">
              <input
                type="text"
                class="form-input"
                placeholder="请输入开户行"
                v-model="settlementForm.bankBranch"
              />
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">银行预留手机号</view>
            <view class="form-value">
              <input
                type="text"
                class="form-input"
                placeholder="请输入银行预留手机号"
                v-model="settlementForm.phone"
              />
            </view>
          </view>
        </template>

        <!-- 企业对公账号 -->
        <template v-if="settlementTab === 'company'">
          <view class="upload-area" @click="uploadPaymentProof">
            <image
              v-if="paymentProofImage"
              :src="paymentProofImage"
              class="upload-image"
              mode="aspectFit"
            ></image>
            <image
              v-else
              src="/static/mine/zfpz.png"
              class="upload-placeholder"
              mode="aspectFit"
            ></image>
            <view class="upload-tip">上传对公支付凭证</view>
          </view>

          <view class="form-item">
            <view class="form-label">账户名称</view>
            <view class="form-value">
              <input
                type="text"
                class="form-input"
                placeholder="请输入账户名称"
                v-model="companyAccountForm.accountName"
              />
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">账户号码</view>
            <view class="form-value">
              <input
                type="text"
                class="form-input"
                placeholder="请输入账户号码"
                v-model="companyAccountForm.accountNumber"
              />
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">所属银行</view>
            <view class="form-value" @click="selectCompanyBank">
              <text
                :class="companyAccountForm.bank ? 'value-text' : 'placeholder'"
              >
                {{ companyAccountForm.bank || "请选择所属银行" }}
              </text>
              <uni-icons type="right" color="#999" size="16"></uni-icons>
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">银行所在地</view>
            <view class="form-value" @click="selectCompanyBankLocation">
              <text
                :class="
                  companyAccountForm.bankLocation ? 'value-text' : 'placeholder'
                "
              >
                {{ companyAccountForm.bankLocation || "请选择银行所在地" }}
              </text>
              <uni-icons type="right" color="#999" size="16"></uni-icons>
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">开户行</view>
            <view class="form-value">
              <input
                type="text"
                class="form-input"
                placeholder="请输入开户行"
                v-model="companyAccountForm.bankBranch"
              />
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">银行预留手机号</view>
            <view class="form-value">
              <input
                type="text"
                class="form-input"
                placeholder="请输入银行预留手机号"
                v-model="companyAccountForm.phone"
              />
            </view>
          </view>
        </template>
      </view>

      <!-- 店铺实控人 -->
      <view v-if="shouldShowController" class="form-section">
        <view class="section-subtitle">实控人信息</view>

        <view class="form-item">
          <view class="form-label">实控人信息</view>
          <view class="form-value" @click="openControllerTypePicker">
            <text :class="controllerType ? 'value-text' : 'placeholder'">
              {{ controllerTypeText }}
            </text>
            <uni-icons type="down" color="#999" size="16"></uni-icons>
          </view>
        </view>

        <view class="upload-section">
          <view class="upload-item">
            <view class="upload-label">人像面</view>
            <view class="upload-desc">上传您的身份证人像面</view>
            <view class="upload-area small" @click="uploadControllerFront">
              <image
                v-if="controllerFrontImage"
                :src="controllerFrontImage"
                class="upload-image"
                mode="aspectFit"
              ></image>
              <image
                v-else
                src="/static/mine/rxm.png"
                class="upload-placeholder"
                mode="aspectFit"
              ></image>
            </view>
          </view>

          <view class="upload-item">
            <view class="upload-label">国徽面</view>
            <view class="upload-desc">上传您的身份证国徽面</view>
            <view class="upload-area small" @click="uploadControllerBack">
              <image
                v-if="controllerBackImage"
                :src="controllerBackImage"
                class="upload-image"
                mode="aspectFit"
              ></image>
              <image
                v-else
                src="/static/mine/ghm.png"
                class="upload-placeholder"
                mode="aspectFit"
              ></image>
            </view>
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">姓名</view>
          <view class="form-value">
            <input
              type="text"
              class="form-input"
              placeholder="请输入姓名"
              v-model="controllerForm.name"
            />
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">身份证号</view>
          <view class="form-value">
            <input
              type="text"
              class="form-input"
              placeholder="请输入身份证号"
              v-model="controllerForm.idNumber"
            />
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">手机号</view>
          <view class="form-value">
            <input
              type="text"
              class="form-input"
              placeholder="请输入手机号"
              v-model="controllerForm.phone"
            />
          </view>
        </view>

        <view class="oral-material">
          <view class="material-title">口播材料</view>
          <view class="material-content">
            <text class="highlight">《禧店科技授权视频》</text>
            并按照承诺进行 截版，录制口播视频上传
          </view>
          <view class="download-btn">查看承诺书</view>
        </view>

        <view class="video-upload">
          <view class="video-title">*承诺视频上传</view>
          <view class="video-desc"
            >请按照口播材料内容，清晰无遮挡朗读并上传视频</view
          >
          <view class="video-actions">
            <view class="video-btn" @click="uploadVideo">
              <uni-icons type="videocam" color="#666" size="40"></uni-icons>
              <text>上传视频</text>
            </view>
            <view class="video-btn primary" @click="recordVideo">
              <uni-icons
                type="videocam-filled"
                color="#fff"
                size="40"
              ></uni-icons>
              <text>示例视频</text>
            </view>
          </view>
          <label class="agreement">
            <view
              class="agreement-checkbox"
              :class="{ checked: agreeProtocol }"
              @click="agreeProtocol = !agreeProtocol"
            >
              <view v-if="agreeProtocol" class="checkbox-inner"></view>
            </view>
            <text class="agreement-text">
              我已阅读并同意
              <text class="highlight">《禧嘉采购用网与责任承担协议》</text>
            </text>
          </label>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view
      class="bottom-actions"
      v-if="!isViewMode"
      :class="{ 'single-btn': isViewMode }"
    >
      <view class="action-btn cancel" @click="goBack">返回</view>
      <view class="action-btn submit" @click="handleSubmit"> 提交 </view>
    </view>

    <!-- 地区选择器 -->
    <RegionPicker
      ref="regionPickerRef"
      v-model="regionData"
      @confirm="handleRegionConfirm"
    />

    <!-- 开始日期选择器 -->
    <DatePicker
      ref="startDatePickerRef"
      v-model="licenseForm.startDate"
      title="选择开始日期"
      @confirm="handleStartDateConfirm"
    />

    <!-- 结束日期选择器 -->
    <DatePicker
      ref="endDatePickerRef"
      v-model="licenseForm.endDate"
      title="选择结束日期"
      @confirm="handleEndDateConfirm"
    />

    <!-- 身份证起效期选择器 -->
    <DatePicker
      ref="idCardStartDatePickerRef"
      v-model="idCardForm.startDate"
      title="选择身份证起效期"
      @confirm="handleIdCardStartDateConfirm"
    />

    <!-- 身份证到期日选择器 -->
    <DatePicker
      ref="idCardEndDatePickerRef"
      v-model="idCardForm.endDate"
      title="选择身份证到期日"
      @confirm="handleIdCardEndDateConfirm"
    />

    <!-- 法人银行卡所在地选择器 -->
    <RegionPicker
      ref="personalBankLocationPickerRef"
      v-model="personalBankRegion"
      @confirm="handlePersonalBankLocationConfirm"
    />

    <!-- 企业对公账号银行所在地选择器 -->
    <RegionPicker
      ref="companyBankLocationPickerRef"
      v-model="companyBankRegion"
      @confirm="handleCompanyBankLocationConfirm"
    />

    <!-- 法人银行卡所属银行选择器 -->
    <BankPicker
      ref="personalBankPickerRef"
      v-model="settlementForm.bank"
      @confirm="handlePersonalBankConfirm"
    />

    <!-- 企业对公账号所属银行选择器 -->
    <BankPicker
      ref="companyBankPickerRef"
      v-model="companyAccountForm.bank"
      @confirm="handleCompanyBankConfirm"
    />

    <!-- 实控人类型选择器 -->
    <uni-popup ref="controllerTypePopup" type="bottom">
      <view class="controller-type-picker">
        <view class="picker-header">
          <text class="picker-title">实控人信息</text>
          <uni-icons
            type="closeempty"
            size="20"
            color="#999"
            class="close-icon"
            @click="closeControllerTypePicker"
          ></uni-icons>
        </view>
        <view class="type-list">
          <view
            class="type-item"
            :class="{ active: controllerType === 'personal' }"
            @click="selectControllerTypeOption('personal')"
          >
            <text class="type-text">个人实控</text>
            <uni-icons
              v-if="controllerType === 'personal'"
              type="checkbox-filled"
              size="20"
              color="#FFA726"
            ></uni-icons>
          </view>
          <view
            class="type-item"
            :class="{ active: controllerType === 'company' }"
            @click="selectControllerTypeOption('company')"
          >
            <text class="type-text">企业实控</text>
            <uni-icons
              v-if="controllerType === 'company'"
              type="checkbox-filled"
              size="20"
              color="#FFA726"
            ></uni-icons>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import DatePicker from "@/components/common/DatePicker/DatePicker.vue";
import RegionPicker from "@/components/common/RegionPicker/RegionPicker.vue";
import BankPicker from "@/components/common/BankPicker/BankPicker.vue";
import { useRequest } from "ahooks-vue";
import { getMerchantInfo } from "@/api/mine";
import { useUserStore } from "@/store/modules/user";
import { useStoreStore } from "@/store/modules/store";

const userStore = useUserStore();
const storeStore = useStoreStore();

// 判断是否为查看模式
const isViewMode = ref(false);

// 页面加载时获取URL参数
onMounted(() => {
  console.log("证照信息页面加载完成");

  // 从本地缓存恢复店铺信息和用户信息
  storeStore.hydrateFromStorage();
  userStore.hydrateFromStorage();

  console.log("商户ID:", storeStore.storeId);
  console.log("用户ID:", userStore.userId);

  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options || {};
  isViewMode.value = options.mode === "view";

  // 加载商户信息
  if (storeStore.storeId && userStore.userId) {
    getMerchantInfoRun();
  } else {
    console.warn("缺少商户ID或用户ID，无法加载商户信息");
    uni.showToast({
      title: "缺少必要信息，请先登录",
      icon: "none",
    });
  }
});

// 选中的变更内容
const selectedItems = reactive({
  license: false, // 营业执照
  legalIdCard: false, // 法人身份证
  settlement: false, // 结算信息
  controller: false, // 店铺实控人
});

// 计算属性：判断各部分是否显示
const shouldShowLicense = computed(() => {
  return isViewMode.value || selectedItems.license;
});

const shouldShowLegalIdCard = computed(() => {
  return isViewMode.value || selectedItems.legalIdCard;
});

const shouldShowSettlement = computed(() => {
  return isViewMode.value || selectedItems.settlement;
});

const shouldShowController = computed(() => {
  return isViewMode.value || selectedItems.controller;
});

// 切换选中状态
const toggleCheckbox = (key) => {
  selectedItems[key] = !selectedItems[key];
};

// 营业执照表单
const licenseForm = reactive({
  name: "",
  address: "",
  creditCode: "",
  startDate: "",
  endDate: "",
  scope: "",
});

const licenseImage = ref("");
const regionText = ref("");
const regionData = ref({
  province: "浙江省",
  city: "杭州市",
  area: "临安区",
});
const regionPickerRef = ref(null);
const startDatePickerRef = ref(null);
const endDatePickerRef = ref(null);
const idCardStartDatePickerRef = ref(null);
const idCardEndDatePickerRef = ref(null);
const personalBankLocationPickerRef = ref(null);
const companyBankLocationPickerRef = ref(null);
const personalBankPickerRef = ref(null);
const companyBankPickerRef = ref(null);
// 银行所在地数据
const personalBankRegion = ref({
  province: "",
  city: "",
  area: "",
});
const companyBankRegion = ref({
  province: "",
  city: "",
  area: "",
});
// 法人身份证表单
const idCardForm = reactive({
  name: "",
  idNumber: "",
  startDate: "",
  endDate: "",
  phone: "",
  address: "",
});
const idCardFrontImage = ref("");
const idCardBackImage = ref("");
// 结算信息表单
const settlementTab = ref("personal"); // personal | company
const settlementForm = reactive({
  cardHolder: "",
  cardNumber: "",
  bank: "",
  bankLocation: "",
  bankBranch: "",
  phone: "",
});
const bankCardFrontImage = ref("");
const bankCardBackImage = ref("");
const paymentProofImage = ref("");
// 企业对公账号表单
const companyAccountForm = reactive({
  accountName: "",
  accountNumber: "",
  bank: "",
  bankLocation: "",
  bankBranch: "",
  phone: "",
});
// 店铺实控人表单
const controllerType = ref("personal"); // personal | company
const controllerTypeText = computed(() => {
  const typeMap = {
    personal: "个人实控",
    company: "企业实控",
  };
  return typeMap[controllerType.value] || "请选择实控人信息";
});
const controllerForm = reactive({
  name: "",
  idNumber: "",
  phone: "",
});
const controllerFrontImage = ref("");
const controllerBackImage = ref("");
const agreeProtocol = ref(false);
const controllerTypePopup = ref(null);

// 获取商户信息
const {
  data: merchantData,
  loading: merchantLoading,
  run: getMerchantInfoRun,
} = useRequest(
  () =>
    getMerchantInfo({
      merchantId: storeStore.storeId,
      userId: userStore.userId,
    }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("获取商户信息成功：", response);
      if (response && response.data) {
        loadMerchantData(response.data);
      }
    },
    onError: (error) => {
      console.error("获取商户信息失败：", error);
      uni.showToast({
        title: "获取商户信息失败",
        icon: "none",
      });
    },
  },
);

// 加载商户数据到表单
const loadMerchantData = (data) => {
  console.log("开始加载商户数据:", data);

  // 营业执照数据
  if (data.businessLicenseFront && data.businessLicenseFront.trim() !== "") {
    licenseImage.value = data.businessLicenseFront;
  }

  // 注册地区
  if (data.province || data.city || data.district) {
    regionData.value = {
      province: data.province || "",
      city: data.city || "",
      area: data.district || "",
    };
    const parts = [];
    if (data.province) parts.push(data.province);
    if (data.city) parts.push(data.city);
    if (data.district) parts.push(data.district);
    if (parts.length > 0) {
      regionText.value = parts.join("/");
    }
  }

  // 营业执照表单数据
  if (data.corporateName && data.corporateName.trim() !== "") {
    licenseForm.name = data.corporateName;
  }
  if (data.storeAddress && data.storeAddress.trim() !== "") {
    licenseForm.address = data.storeAddress;
  }
  // creditCode, startDate, endDate, scope 接口未返回,保持默认值

  // 法人身份证图片
  if (data.idCardFront && data.idCardFront.trim() !== "") {
    idCardFrontImage.value = data.idCardFront;
  }
  if (data.idCardBack && data.idCardBack.trim() !== "") {
    idCardBackImage.value = data.idCardBack;
  }
  if (data.idCardHold && data.idCardHold.trim() !== "") {
    // 手持身份证照片(如果需要展示)
    // idCardHoldImage.value = data.idCardHold;
  }

  // 法人身份证表单数据
  if (data.userName && data.userName.trim() !== "") {
    idCardForm.name = data.userName;
  }
  if (data.idCard && data.idCard.trim() !== "") {
    idCardForm.idNumber = data.idCard;
  }
  if (data.userMobile && data.userMobile.trim() !== "") {
    idCardForm.phone = data.userMobile;
  }
  // startDate, endDate, address 接口未返回,保持默认值

  // 门店图片(可以在页面其他地方展示)
  // storePicture1, storePicture2, storePicture3, storeLargePicture

  console.log("商户数据已加载到表单");
  console.log("营业执照表单:", licenseForm);
  console.log("身份证表单:", idCardForm);
  console.log("注册地区:", regionData.value);
};

// 获取审核状态文本
const getAuditStatusText = (status) => {
  switch (status) {
    case -1:
      return "未申请";
    case 0:
      return "审核中";
    case 1:
      return "已通过";
    case 2:
      return "已拒绝";
    default:
      return "未知";
  }
};

// 获取审核状态样式类
const getAuditStatusClass = (status) => {
  switch (status) {
    case -1:
      return "status-not-applied";
    case 0:
      return "status-pending";
    case 1:
      return "status-approved";
    case 2:
      return "status-rejected";
    default:
      return "";
  }
};

// 获取完整地址
const getFullAddress = (data) => {
  const parts = [];
  if (data.province) parts.push(data.province);
  if (data.city) parts.push(data.city);
  if (data.district) parts.push(data.district);
  if (data.storeAddress) parts.push(data.storeAddress);
  return parts.join("");
};

// 上传营业执照
const uploadLicense = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      licenseImage.value = res.tempFilePaths[0];
    },
  });
};

// 选择地区
const selectRegion = () => {
  regionPickerRef.value?.open();
};

// 地区确认
const handleRegionConfirm = (region) => {
  regionData.value = region;
  regionText.value = `${region.province}/${region.city}/${region.area}`;
};

// 选择开始日期
const selectStartDate = () => {
  startDatePickerRef.value?.open();
};

// 开始日期确认
const handleStartDateConfirm = (date) => {
  licenseForm.startDate = date;
};

// 选择结束日期
const selectEndDate = () => {
  endDatePickerRef.value?.open();
};

// 结束日期确认
const handleEndDateConfirm = (date) => {
  licenseForm.endDate = date;
};

// 选择身份证起效期
const selectIdCardStartDate = () => {
  idCardStartDatePickerRef.value?.open();
};

// 身份证起效期确认
const handleIdCardStartDateConfirm = (date) => {
  idCardForm.startDate = date;
};

// 选择身份证到期日
const selectIdCardEndDate = () => {
  idCardEndDatePickerRef.value?.open();
};

// 身份证到期日确认
const handleIdCardEndDateConfirm = (date) => {
  idCardForm.endDate = date;
};

// 上传身份证人像面
const uploadIdCardFront = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      idCardFrontImage.value = res.tempFilePaths[0];
    },
  });
};

// 上传身份证国徽面
const uploadIdCardBack = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      idCardBackImage.value = res.tempFilePaths[0];
    },
  });
};

// 上传银行卡正面
const uploadBankCardFront = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      bankCardFrontImage.value = res.tempFilePaths[0];
    },
  });
};

// 上传银行卡反面
const uploadBankCardBack = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      bankCardBackImage.value = res.tempFilePaths[0];
    },
  });
};

// 上传对公支付凭证
const uploadPaymentProof = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      paymentProofImage.value = res.tempFilePaths[0];
    },
  });
};

// 选择法人银行卡所属银行
const selectPersonalBank = () => {
  personalBankPickerRef.value?.open();
};

// 法人银行卡所属银行确认
const handlePersonalBankConfirm = (bankName) => {
  settlementForm.bank = bankName;
};

// 选择法人银行卡所在地
const selectPersonalBankLocation = () => {
  personalBankLocationPickerRef.value?.open();
};

// 法人银行卡所在地确认
const handlePersonalBankLocationConfirm = (region) => {
  personalBankRegion.value = region;
  settlementForm.bankLocation = `${region.province}/${region.city}/${region.area}`;
};

// 选择企业对公账号所属银行
const selectCompanyBank = () => {
  companyBankPickerRef.value?.open();
};

// 企业对公账号所属银行确认
const handleCompanyBankConfirm = (bankName) => {
  companyAccountForm.bank = bankName;
};

// 选择企业对公账号银行所在地
const selectCompanyBankLocation = () => {
  companyBankLocationPickerRef.value?.open();
};

// 企业对公账号银行所在地确认
const handleCompanyBankLocationConfirm = (region) => {
  companyBankRegion.value = region;
  companyAccountForm.bankLocation = `${region.province}/${region.city}/${region.area}`;
};

// 打开实控人类型选择器
const openControllerTypePicker = () => {
  controllerTypePopup.value?.open();
};

// 关闭实控人类型选择器
const closeControllerTypePicker = () => {
  controllerTypePopup.value?.close();
};

// 选择实控人类型
const selectControllerTypeOption = (type) => {
  controllerType.value = type;
  closeControllerTypePicker();
};

// 上传实控人身份证人像面
const uploadControllerFront = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      controllerFrontImage.value = res.tempFilePaths[0];
    },
  });
};

// 上传实控人身份证国徽面
const uploadControllerBack = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      controllerBackImage.value = res.tempFilePaths[0];
    },
  });
};

// 上传视频
const uploadVideo = () => {
  uni.chooseVideo({
    count: 1,
    success: (res) => {
      uni.showToast({
        title: "视频上传成功",
        icon: "none",
      });
    },
  });
};

// 录制视频
const recordVideo = () => {
  uni.chooseVideo({
    sourceType: ["camera"],
    success: (res) => {
      uni.showToast({
        title: "视频录制成功",
        icon: "none",
      });
    },
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 提交表单
const handleSubmit = () => {
  // 检查是否至少选中了一项
  const hasSelected = Object.values(selectedItems).some((item) => item);
  if (!hasSelected) {
    uni.showToast({
      title: "请至少选择一项变更内容",
      icon: "none",
    });
    return;
  }

  // TODO: 实现提交逻辑
  uni.showToast({
    title: "提交成功",
    icon: "none",
  });
};

// 加载模拟数据（查看模式）
const loadMockData = () => {
  // 营业执照数据
  licenseImage.value = "/static/mine/yyzz.png";
  regionData.value = {
    province: "浙江省",
    city: "杭州市",
    area: "临安区",
  };
  regionText.value = "浙江省/杭州市/临安区";
  Object.assign(licenseForm, {
    name: "杭州临安嘉智行源信息咨询工作室（个体工商户）",
    address: "浙江省杭州市临安区锦北街道科技大道同人山庄星岸南苑1幢101-407#1位",
    creditCode: "92330185MAD4WNGK74",
    startDate: "2020-03-01",
    endDate: "2099-12-31",
    scope:
      "一般项目：信息咨询服务（不含许可类信息咨询服务）；技术服务、技术开发、技术咨询、技术交流、技术转让、技术推广；市场营销策划；社会经济咨询服务；企业管理；企业管理咨询（除依法须经批准的项目外，凭营业执照依法自主开展经营活动）。",
  });

  // 法人身份证数据
  idCardFrontImage.value = "/static/mine/rxm.png";
  idCardBackImage.value = "/static/mine/ghm.png";
  Object.assign(idCardForm, {
    name: "叶来弟",
    idNumber: "362334198111174629",
    startDate: "2010-03-01",
    endDate: "2030-03-01",
    phone: "18868706377",
    address: "江西省上饶市婺源县大鄣山乡和村58号",
  });

  // 结算信息数据 - 法人银行卡
  bankCardFrontImage.value = "/static/mine/yhkzm.png";
  bankCardBackImage.value = "/static/mine/yhkfm.png";
  personalBankRegion.value = {
    province: "浙江省",
    city: "杭州市",
    area: "临安区",
  };
  Object.assign(settlementForm, {
    cardHolder: "叶来弟",
    cardNumber: "6228480328881133172",
    bank: "中国农业银行",
    bankLocation: "浙江省/杭州市/临安区",
    bankBranch: "中国农业银行",
    phone: "18868706377",
  });

  // 结算信息数据 - 企业对公账号
  paymentProofImage.value = "/static/mine/zfpz.png";
  companyBankRegion.value = {
    province: "浙江省",
    city: "杭州市",
    area: "临安区",
  };
  Object.assign(companyAccountForm, {
    accountName: "杭州临安嘉智行源信息咨询工作室",
    accountNumber: "6228480328881133172",
    bank: "中国农业银行",
    bankLocation: "浙江省/杭州市/临安区",
    bankBranch: "中国农业银行",
    phone: "18868706377",
  });

  // 店铺实控人数据
  controllerFrontImage.value = "/static/mine/rxm.png";
  controllerBackImage.value = "/static/mine/ghm.png";
  Object.assign(controllerForm, {
    name: "叶来弟",
    idNumber: "362334198111174629",
    phone: "18868706377",
  });
};
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.content {
  padding: 20rpx 32rpx;
}

// 审核状态卡片
.audit-status-card {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 32rpx;
  margin-bottom: 32rpx;
}

.status-row {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
  padding-bottom: 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.status-label {
  font-size: 28rpx;
  color: #666;
  margin-right: 16rpx;
}

.status-value {
  font-size: 28rpx;
  font-weight: 600;

  &.status-not-applied {
    color: #999;
  }

  &.status-pending {
    color: #ff9900;
  }

  &.status-approved {
    color: #4caf50;
  }

  &.status-rejected {
    color: #f44336;
  }
}

.info-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.info-label {
  font-size: 28rpx;
  color: #666;
  min-width: 140rpx;
  flex-shrink: 0;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  word-break: break-all;
}

.qrcode-row {
  flex-direction: column;
  align-items: flex-start;
}

.qrcode-image {
  width: 200rpx;
  height: 200rpx;
  margin-top: 16rpx;
  border: 1rpx solid #f0f0f0;
  border-radius: 8rpx;
}

.section-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 600;
  margin-bottom: 24rpx;
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
  margin-bottom: 40rpx;
}

.checkbox-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
  width: calc(50% - 12rpx);
}

.checkbox-box {
  width: 36rpx;
  height: 36rpx;
  border: 2rpx solid #ddd;
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;

  &.checked {
    background-color: #ffbb00;
    border-color: #ffbb00;
  }
}

.checkbox-label {
  font-size: 28rpx;
  color: #333;
}

.form-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 32rpx;
  margin-bottom: 32rpx;
}

.section-subtitle {
  font-size: 30rpx;
  color: #333;
  font-weight: 600;
  margin-bottom: 32rpx;
}

.upload-area {
  background-color: #f8f8f8;
  border-radius: 12rpx;
  padding: 40rpx;
  text-align: center;
  margin-bottom: 32rpx;
  position: relative;

  &.small {
    padding: 20rpx;
    margin-bottom: 0;
  }
}

.upload-placeholder,
.upload-image {
  width: 100%;
  height: 300rpx;
  margin-bottom: 16rpx;
}

.small .upload-placeholder,
.small .upload-image {
  height: 240rpx;
}

.upload-tip {
  font-size: 24rpx;
  color: #999;
}

.upload-section {
  display: flex;
  gap: 24rpx;
  margin-bottom: 32rpx;
}

.upload-item {
  flex: 1;
}

.upload-label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.upload-desc {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 16rpx;
}

.form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f0f0f0;

  &.column {
    flex-direction: column;
    align-items: flex-start;
  }

  &:last-child {
    border-bottom: none;
  }
}

.form-label {
  font-size: 28rpx;
  color: #333;
  flex-shrink: 0;
  margin-bottom: 8rpx;
}

.form-value {
  display: flex;
  align-items: center;
  gap: 8rpx;
  flex: 1;
  justify-content: flex-end;
}

.form-value-full {
  width: 100%;
  margin-top: 8rpx;
}

.value-text {
  font-size: 28rpx;
  color: #666;
  text-align: right;
  word-break: break-all;
}

.placeholder {
  font-size: 28rpx;
  color: #999;
}

.form-input {
  font-size: 28rpx;
  color: #333;
  text-align: right;
  width: 100%;
}

.tab-group {
  display: flex;
  gap: 32rpx;
  margin-bottom: 32rpx;
}

.tab-item {
  font-size: 28rpx;
  color: #666;
  padding-bottom: 8rpx;
  position: relative;

  &.active {
    color: #ffbb00;
    font-weight: 600;

    &::after {
      content: "";
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 4rpx;
      background-color: #ffbb00;
      border-radius: 2rpx;
    }
  }
}

.oral-material {
  background-color: #fff9e6;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-top: 32rpx;
}

.material-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 600;
  margin-bottom: 12rpx;
}

.material-content {
  font-size: 24rpx;
  color: #666;
  line-height: 36rpx;
  margin-bottom: 16rpx;
}

.highlight {
  color: #ffbb00;
  font-weight: 500;
}

.download-btn {
  background-color: #ffbb00;
  color: #fff;
  font-size: 28rpx;
  text-align: center;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  display: inline-block;
}

.video-upload {
  margin-top: 32rpx;
}

.video-title {
  font-size: 28rpx;
  color: #ff0000;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.video-desc {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 24rpx;
}

.video-actions {
  display: flex;
  gap: 24rpx;
  margin-bottom: 24rpx;
}

.video-btn {
  flex: 1;
  background-color: #f5f5f5;
  border: 2rpx dashed #ddd;
  border-radius: 12rpx;
  padding: 40rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16rpx;

  &.primary {
    background-color: #ffbb00;
    border-color: #ffbb00;

    text {
      color: #fff;
    }
  }

  text {
    font-size: 24rpx;
    color: #666;
  }
}

.agreement {
  display: flex;
  align-items: flex-start;
  gap: 12rpx;
}

.agreement-checkbox {
  width: 32rpx;
  height: 32rpx;
  border: 2rpx solid #ddd;
  border-radius: 50%;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 4rpx;

  &.checked {
    border-color: #ffbb00;
  }
}

.checkbox-inner {
  width: 20rpx;
  height: 20rpx;
  background-color: #ffbb00;
  border-radius: 50%;
}

.agreement-text {
  font-size: 24rpx;
  color: #666;
  line-height: 36rpx;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 32rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  display: flex;
  gap: 24rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.05);

  &.single-btn {
    justify-content: center;

    .action-btn {
      flex: 0 0 auto;
      min-width: 300rpx;
    }
  }
}

.action-btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 500;

  &.cancel {
    background-color: #f5f5f5;
    color: #666;
  }

  &.submit {
    background-color: #ffbb00;
    color: #fff;
  }
}

.controller-type-picker {
  background: #fff;
  border-radius: 16rpx 16rpx 0 0;
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 32rpx;
  border-bottom: 1rpx solid #f5f5f5;
  position: relative;
}

.picker-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.close-icon {
  position: absolute;
  right: 32rpx;
  top: 50%;
  transform: translateY(-50%);
}

.type-list {
  padding: 16rpx 0;
  padding-bottom: calc(16rpx + env(safe-area-inset-bottom));
}

.type-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  transition: background-color 0.2s;

  &:active {
    background-color: #f9f9f9;
  }

  &.active {
    background-color: #fff7f0;
  }
}

.type-text {
  font-size: 28rpx;
  color: #333;
}
</style>
